# -*- coding:utf-8 -*-
from __future__ import annotations
import aioredis
import os
from fastapi import FastAPI

class RedisStorage:
    @staticmethod
    async def init_redis(app: FastAPI) -> None:  # pragma: no cover
        """
        系统缓存
        :return: cache 连接池
        """
        # 从URL方式创建redis连接池
        host = os.getenv('REDIS_HOST', '127.0.0.1')
        port = int(os.getenv('REDIS_PORT', 6379))
        db = int(os.getenv('REDIS_DB', 1))
        pwd = os.getenv('REDIS_PASSWORD', '123123')

        app.state.redis_pool = aioredis.ConnectionPool.from_url(
            f"redis://{host}:{port}",
            db=db,
            encoding='utf-8',
            decode_responses=True,
            password=pwd
        )

    @staticmethod
    async def shutdown_redis(app: FastAPI) -> None:  # pragma: no cover
        """
        Closes redis connection pool.

        :param app: current FastAPI app.
        """
        await app.state.redis_pool.disconnect()


    @classmethod
    async def close_redis_pool(cls, app) -> None:
        """
        应用关闭时关闭redis连接
        :param app: fastapi对象
        :return:
        """
        await app.state.redis.close()

    @classmethod
    async def get_cache_object(cls, app: FastAPI, key: str) -> str | None:
        async with aioredis.Redis(connection_pool=app.state.redis_pool) as redis:
            return await redis.get(key)

    @classmethod
    async def set_cache_object(cls, app: FastAPI, key: str, value:str, ttl: int=0) -> None:
        async with aioredis.Redis(connection_pool=app.state.redis_pool) as redis:
            if ttl>0:
                await redis.set(key, value, ttl)
            else:
                await redis.set(key, value)
            await redis.save()

    @classmethod
    async def decrease(cls, app: FastAPI, key:str) -> None:
        async with aioredis.Redis(connection_pool=app.state.redis_pool) as redis:
            ttl = await redis.ttl(key)
            await redis.decr(key, 1)
            await redis.expire(key, ttl)